<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 登录
 * @author Administrator
 *
 */
class Login extends MY_Controller {
	
	/**
	 * 首页
	 */
	public function index(){
		
		if($_POST){
			//表单验证
			$vConf = array(
						array('account', '账号', 'required'),
						array('password', '密码', 'required|min_length[6]|max_length[15]'),
						array('captcha', '验证码', 'required')
					);
			$this->formDataValidation($vConf);
			
			$account = $this->input->post('account');
			$password = setPassword($this->input->post('password'));
			$captcha = $this->input->post('captcha');
			$cCaptcha = get_cookie('captcha');
			if($captcha != $cCaptcha){
				$this->ajaxReturn(0, '验证码错误');			
			}
			
			$tA = $this->mUser->getUserInfoByAccountAndPassword($account, $password);
			if($tA){
				if($tA['status'] != 2){
					$this->ajaxReturn(0, '你的账号已被停用');		
				}
				
				$key = config_item('encryption_key');
				$sessionId = encryption($tA['id'].$tA['name'].$key.time().mt_rand(10,1000));
				if($this->mUser->addUserSession($tA['id'], $sessionId)){
        			setcookie('admin_sessionid', encode($sessionId), 0, '/');
					$this->ajaxReturn(1, '', '', getUrl('home'));
				}
			}
			
			$this->ajaxReturn(0, '手机号码或密码错误');
		}
		
		$this->view('login');
	}
	
	/**
     * 生成验证码
     *
     * @return void
     */
    public function captcha(){
    	
    	$this->load->helper('cookie');
        $captcha = '';
        for($i = 0; $i < 4; $i ++){
        	$captcha .= dechex(mt_rand(1, 15));
        }
        
        setcookie('captcha', $captcha);
        setcookie('captcha', $captcha, 0, '/');
        $im = imagecreate(80, 35);
        $white = imagecolorallocate($im, 255, 255, 255);
        $black = imagecolorallocate($im, 0, 0, 0);

        for($i = 0; $i < 100; $i ++){
        	$color = ImageColorAllocate($im, mt_rand(100, 255), mt_rand(100, 255),
        								 mt_rand(100, 255));
        	ImageSetPixel($im, mt_rand(0, 70), mt_rand(0, 30), $color);
        }
        
        imagestring($im, 5, 10, 10, $captcha, $black);
        imagepng($im);
        imagedestroy($im);
    }
    
	/**
     * 退出登录
     * 
     * @return void
     */
    public function out(){
    
    	$sessionId = decode(get_cookie('admin_sessionid'));
    	if($this->mUser->deleteSessionId($sessionId)){
        	setcookie('admin_sessionid', '', 0, '/');
	    	redirect(getUrl('login'));
    	}
    	
    	show_error('退出登录失败');
    }
}
